package com.frame.util;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import com.jfinal.plugin.activerecord.Record;

/**
 * @author LRC
 * @createDate 2015年5月30日
 * @description miniui相关参数工具类
 */
public class MiniuiUtil {

	/**
	 * @updateTeim 2015年5月30日下午8:24:00
	 * @description
	 * @param data
	 * @param c
	 * @return
	 */
	public static Map<String, List<Record>> parseGridChange(String data, String idColumn) {
		
		List<Record> deleteIds = new ArrayList<Record>();
		List<Record> updateDatas = new ArrayList<Record>();
		List<Record> insertDatas = new ArrayList<Record>();
		JSONArray array = JSONArray.fromObject(data);
		for (int i = 0; i < array.size(); i++) {
			JSONObject json = array.getJSONObject(i);
			Record obj = parserToRecord(json);
			String _state = json.getString("_state");
			Object id = obj.get(idColumn);
			if ("added".equals(_state) || id == null) // 新增：id为空，或_state为added
			{
				insertDatas.add(obj);
			} else if ("removed".equals(_state)) {
				deleteIds.add(obj);
			} else if ("modified".equals(_state)) // 更新：_state为空，或modified
			{
				updateDatas.add(obj);
			}
		}
		Map<String, List<Record>> map = new HashMap<String, List<Record>>();
		map.put("insert", insertDatas);
		map.put("update", updateDatas);
		map.put("delete", deleteIds);

		return map;
	}

	public static Set<String> expectKey = new TreeSet<String>();
	static {
		expectKey.add("_id");
		expectKey.add("_uid");
		expectKey.add("_state");
	}
	public static Map parserToMap(String s) {
		Map map = new HashMap();
		JSONObject json = JSONObject.fromObject(s);
		Iterator keys = json.keys();
		while (keys.hasNext()) {
			String key = (String) keys.next();
			String value = json.get(key).toString();
			if (value.startsWith("{") && value.endsWith("}")) {
				map.put(key, parserToMap(value));
			} else {
				map.put(key, value);
			}
		}
		return map;
	}

	public static Record parserToRecord(JSONObject json) {
		Record record = new Record();
		Iterator keys = json.keys();
		while (keys.hasNext()) {
			String key = (String) keys.next();
			if (expectKey.contains(key))
				continue;
			Object value = json.get(key);
			String _value = json.getString(key);
			//对null值做特殊处理
			if(value==null||"null".equals(_value)||_value=="null"){
				Date date = null;
				record.set(key, date);
			}else{
				// 暂时先不错属性类型解析，统一为字符串
				record.set(key, value);
			}
		}
		return record;
	}
}
